package utils

import (
	"reflect"
	"slices"
	"strings"
)

// 解析结构体标签，将其转换为map[string]string格式
func ParseTags(tag string) map[string]interface{} {
	tags := make(map[string]interface{})
	pairs := strings.Split(tag, ";")
	for _, pair := range pairs {
		str := strings.Split(pair, ":")
		if len(str) == 2 {
			tags[str[0]] = strings.Split(str[1], ",")[0]
		}
	}
	return tags
}

// 获取结构体所有标签并放入map中
func StructTags(s interface{}, target string) map[string]map[string]interface{} {
	result := make(map[string]map[string]interface{})
	t := reflect.TypeOf(s)
	index := 0
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		/*
			* todo: 结构体嵌套处理，暂不支持
			if field.Type.Kind() == reflect.Struct {
				sub := reflect.New(field.Type).Elem()
				result = StructTags(sub.Interface())
			}
		*/
		// gorm.Model 特殊处理
		if field.Name == "Model" {
			result["ID"] = map[string]interface{}{
				"label": "ID",
				"name":  "ID",
				"index": i,
			}
			index++
			continue
		}
		ignoreTags := strings.Split(field.Tag.Get("ignore"), ",")

		if slices.Contains(ignoreTags, target) {
			continue
		}
		tags := ParseTags(field.Tag.Get("amis"))
		tagJson := field.Tag.Get("json")
		if tags["name"] == nil {
			if tagJson == "" {
				tagJson = field.Name
			} else {
				tagJson = strings.Split(tagJson, ",")[0]
			}
			tags["name"] = tagJson
		}
		tags["index"] = index
		result[field.Name] = tags
		index++
	}
	return result
}
